<?php

//defined('BASE_MAPPER_DEFAULT') || 
// define('BASE_MAPPER_DEFAULT', -8001 );

//defined('BASE_MAPPER_DEFAULT_ITEMS_PER_PAGE') || 
// define('BASE_MAPPER_DEFAULT_ITEMS_PER_PAGE', 20 );

class BaseMapper
{
    const DEFAULT_ROW_COUNT = 5;
    protected $_db = null;

    public function getDb()
    {
        if( !$this->_db ) {
            $this->_db = new $this->_dbTableName();
        }
        return $this->_db;
    }
    /*
    public function setDb( $db )
    {
        $this->_db = $db;
        return $this; 
    }
    */

    public function getModel()
    {
        return new $this->_modelName();
    }

    //================================================================================
    // about read
    //================================================================================

    protected function _find($id)
    {
        /*
            $this->getDb()->find(array(1, 2, 3));
        */
        
        $result = $this->getDb()->find($id);  
        if (0 == count($result)) {  
            return;  
        }  
        $row = $result->current();  
        $model = $this->mapRow( $row->toArray() );
        return $model;
    }


    //================================================================================
    // about write update delete
    //================================================================================

    /**
     *  add or update
     *  
     */
    protected function _save( $model, $mode )
    {

        if( !is_object($model) ) {
            return false;
        }

        try {

            $data = $model->toArray();
            foreach( $data as $field => $value ) {
                if( is_array($value) ) {
                    $data[$field] = serialize($value);
                }
            }

            if('add'==$mode) {
                unset($data['id']);  
                // return insert id
                return $this->getDb()->insert($data);  
            }
            elseif('update'==$mode) {
                // return rows affected
                return $this->getDb()->update($data, array('id = ?' => $data['id']));  
            }

        }
        catch(Exception $e) {
/*
            echo '<pre style="background-color:#def;color:#000;text-align:left;font-size:10px;font-family:dina,GulimChe;">';
            print_r($e);
            echo "</pre>\n";
*/
            /*
            // 1062 ???????????
            if( preg_match('/1062\ Duplicate\ entry/',$e->getMessage()) ) {
                $this->_error['save']['code']    = 'mysql-1062';
                $this->_error['save']['message'] = '資料已存在, 無法儲存, 應該是帳號或是email有重覆';
                return false;
            }
            */
        }

    }

    /**
     *  delete
     */
    protected function _delete( $fields=Array() )
    {
        if( !$fields || !is_array($fields) ) {
            return 0;
        }
        
        foreach( $fields as $key => $value ) {
            $where[] = $this->getDb()->getAdapter()->quoteInto(" {$key} = ? ", $value );
        }
        $where = join(' AND ',$where);
        return $this->getDb()->delete($where);
    }

    //================================================================================
    // tools
    //================================================================================

    /**
     * 用來檢查 _getByQuery() 代入的 $opt 變數是否輸入錯誤
     * 算是一種 開發程式時 的 補助工具
     */
    protected function _checkOption( $opt ) 
    {
        if( !$opt ) {
            return true;
        }
        
        // validate opt variable
        $tableFields = $this->getModel()->getTableFields();
        foreach( $opt as $variableName => $variableValue ) {
            
            if( '_' == substr($variableName,0,1) ) {
                // 不檢查開頭為 _ 的變數
                continue;
            }

            $allow = false;
            foreach( $tableFields as $field => $method ) {

                $varName = substr($method,3);
                $varName = (string)(strtolower(substr($varName,0,1)).substr($varName,1)); // 開頭轉小寫
                if( $variableName === $varName ) {
                    $allow = true;
                    break;
                }
            }
            if( !$allow ) {
                throw new Exception("program error - {$variableName} 是錯誤的參數名稱");
            }

        }
    }

}
